//
//  ComposeViewController.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/15.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {

    override func loadView() {
      view = UIView()
      setUpUI()
    }
//    微博文本长度
     let maxLength = 120
//    MARK: - 懒加载
    /// 工具栏
    private lazy var toolBar = UIToolbar()
    /// 文本视图
    private lazy var textView: UITextView = {
       let tv = UITextView()
       tv.textColor = UIColor.darkGrayColor()
       tv.font = UIFont.systemFontOfSize(18)
       tv.alwaysBounceVertical = true
       tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
       tv.delegate = self
       return tv
    }()
    /// 占位标签
    private lazy var placeHolder:UILabel = UILabel(title: "分享新鲜事", fontSize: 18, color: UIColor.lightGrayColor())
    /// 长度提示标签
//    var maxLengthLabel:UILabel {
//       return UILabel(title: "\(maxLength)", fontSize: 12)
//    }
    private lazy var maxLengthLabel:UILabel = UILabel(title: "还可输入120字", fontSize: 12)
     /// 图片选择控制器
    private lazy var picturePickerController = PicturePickerViewController()
    //MARK: -  监听方法
    @objc private func selectEmoticon(){
     textView.resignFirstResponder()
     textView.inputView = textView.inputView == nil ? emoticonView:nil
     textView.becomeFirstResponder()
    }
    /// 自定义键盘
    private lazy var emoticonView:EmoticonView = EmoticonView {
       [weak self] (emoticon) -> ()
        in
        self?.textView.insertEmoticon(emoticon)
    }

    @objc func close (){
        dismissViewControllerAnimated(true, completion: nil)
        textView.resignFirstResponder()
    }
    @objc func sendStatus(){
     let text = textView.emoticonText
        if text.characters.count >= maxLength{
            SVProgressHUD.showSuccessWithStatus("输入内容过长内容",maskType: .Gradient)
            return
        }
        
     NetWorkTools.sharedTools.sendStatus(text,image:picturePickerController.pictures.last) { (result, error) -> () in
        
        if error != nil{
            SVProgressHUD.showErrorWithStatus("您的网络梦游了~",maskType: .Gradient)
            return
        }
        self.close()
        }
    }
    
    /// 选择照片
    @objc private func selectPicture() {
        print("选择照片 \(picturePickerController.view.frame)")
        
        // 退掉键盘
        textView.resignFirstResponder()
        
        // 0. 判断如果已经更新了约束，不再执行后续代码
        if picturePickerController.view.frame.height > 0 {
            picturePickerController.view.snp_updateConstraints(closure: { (make) -> Void in
            })
            return
        }
        
        // 1. 修改照片选择控制器视图的约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        // 2. 修改文本视图的约束 - 重建约束 - 会将之前`textView`的所有的约束删除
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        // 3. 动画更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    

    
    @objc func keyboardChanged(n:NSNotification){
        print(n)
        
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -view.bounds.height + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(duration) {
//            设置动画曲线
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    //    MARK: - 激活键盘
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    //    MARL: - 键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector:"keyboardChanged:",
            name:  UIKeyboardWillChangeFrameNotification,
            object: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
//MARK: - 设置界面
extension ComposeViewController{
    
    func setUpUI(){
//       0 背景颜色
        view.backgroundColor = UIColor.whiteColor()
        automaticallyAdjustsScrollViewInsets = false
//       1 导航条
        prepareNavigationBar()
//       2 底部工具栏 toolBar
        prepareBottomToolBar()
//       3 准备文本框
        prepareTextView()
        preparePicker()
    }
//MARK: - 准备导航条
    func prepareNavigationBar(){
//        1 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "关闭",
            style: .Plain,
            target: self,
            action: "close")
        
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "发布",
            style: .Plain,
            target: self,
            action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
//        2 标题视图
        let titleView = UIView(frame:CGRect(x: 0, y: 0, width: 200, height: 36))
        let titleLabel = UILabel(title: "发微博", fontSize: 15, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleLabel.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        navigationItem.titleView = titleView
    }
//MARK: - 准备底部工具栏
    func prepareBottomToolBar(){
//        1 添加控件
        view.addSubview(toolBar)
//        2 背景颜色
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
//        3 自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
//        4 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings{
           let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
//    MARK: -  准备文本视图
    private func prepareTextView(){
        view.addSubview(textView)
        textView.addSubview(placeHolder)
        view.addSubview(maxLengthLabel)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        maxLengthLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(textView.snp_bottom).offset(-8)
            make.right.equalTo(textView.snp_right).offset(-5)
        }
        
        textView.text = "分享新鲜事"
     
    }
    
//    MARK: - 准备照片选择器
  private func preparePicker(){
//    0 添加子控制器
    addChildViewController(picturePickerController)
//    1 添加视图
     view.insertSubview(picturePickerController.view, belowSubview: toolBar)
//    2 自动布局
    picturePickerController.view.snp_makeConstraints { (make) -> Void in
        make.bottom.equalTo(view.snp_bottom)
        make.left.equalTo(view.snp_left)
        make.right.equalTo(view.snp_right)
        make.height.equalTo(0)
    }
    
    }
}

extension ComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        let canIn = maxLength - textView.text.characters.count
         placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        if canIn > 0{
            maxLengthLabel.text = "还可输入\(canIn)字"
            return
        }
        navigationItem.rightBarButtonItem?.enabled = false
    }
}
